package code.class3.easy;

/**
 * https://leetcode.cn/problems/check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence/
 * 检查单词是否为句中其他单词的前缀
 * 解题思路：
 * 1.使用双指针算法， p1 和 p2同时走
 * 2.当p2能走完时，则说明p2是p1所在字符串的前缀字符串
 */
public class Code07_isPrefixOfWord {
    public static void main(String[] args) {
        String str = "i love eating burger";
        String searchWord = "burg";
        int prefixOfWord = isPrefixOfWord(str, searchWord);
        System.out.println("prefixOfWord = " + prefixOfWord);
    }

    public static int isPrefixOfWord(String sentence, String searchWord) {
        String[] strArr = sentence.split(" ");
        char[] arr = searchWord.toCharArray();
        for (int i = 0; i < strArr.length; i++) {
            int p1 = 0, p2 = 0; // 定义双指针
            char[] temp = strArr[i].toCharArray();
            // p1和 p2 同时走
            while (p1 < temp.length && p2 < arr.length) {
                if (temp[p1] == arr[p2]) {
                    p1++;
                    p2++;
                } else {
                    break;
                }
            }
            // 当while跳出循环时，如果p2已经走完，则说明p2是p1所在字符串的前缀
            if (p2 == arr.length) {
                return i + 1;
            }
        }
        return -1;
    }
}
